package com.gzhryc.net_marketing.api;

import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.net_marketing.api.protocol.order.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;

public class CloudGoodsOrderAPIService {

    private static Logger log = Logger.getLogger(CloudGoodsOrderAPIService.class);

    private static CloudGoodsOrderAPIService me;

    public static CloudGoodsOrderAPIService self() {
        if(me == null) {
            me = new CloudGoodsOrderAPIService();
        }
        return me;
    }

    private CloseableHttpClient httpClient;
    private String cloudApiHttpDomain;

    public void initial(String cloudApiHttpDomain) {
        this.httpClient = HttpClients.createDefault();
        this.cloudApiHttpDomain = cloudApiHttpDomain;
    }

    /**
     * 创建云商品订单
     * @param apiReq
     * @return
     */
    public CreateSupplierGoodsOrderResponse createGoodsOrder(CreateSupplierGoodsOrderRequest apiReq) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/goods/order/create.do").build();

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("创建云商品订单返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    CreateSupplierGoodsOrderResponse apiResp = JsonTools.fromJson(str, CreateSupplierGoodsOrderResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("创建云商品订单错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 获取云商品订单
     * @param tradeNo
     * @return
     */
    public GetSupplierGoodsOrderResponse getGoodsOrder(String tradeNo) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/goods/order/get.do").build();

            GetSupplierGoodsOrderRequest apiReq = new GetSupplierGoodsOrderRequest();
            apiReq.getBody().setTradeNo(tradeNo);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("云商品订单返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    GetSupplierGoodsOrderResponse apiResp = JsonTools.fromJson(str, GetSupplierGoodsOrderResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("云商品订单错误，" + e.getMessage(), e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 确认云商品订单
     * @param apiReq
     * @return
     */
    public DefaultAPIResponse confirmGoodsOrder(ConfirmGoodsOrderRequest apiReq){
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/order/goods/confirm.do").build();

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("云订单确认请求返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    DefaultAPIResponse apiResp = JsonTools.fromJson(str, DefaultAPIResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("云订单确认请求错误，" + e.getMessage(), e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public DefaultAPIResponse updateGoodsOrderState(UpdateGoodsOrderStateRequest apiReq){
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/order/goods/state/update.do").build();

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("云订单状态变更返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    DefaultAPIResponse apiResp = JsonTools.fromJson(str, DefaultAPIResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("云订单状态变更错误，" + e.getMessage(), e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 修改云商品订单的收货地址
     * @param apiReq
     * @return
     */
    public UpdateGoodsOrderAddressResponse updateGoodsOrderAddress(UpdateGoodsOrderAddressRequest apiReq) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/goods/order/address/update.do").build();

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("修改云商品订单收货地址返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    UpdateGoodsOrderAddressResponse apiResp = JsonTools.fromJson(str, UpdateGoodsOrderAddressResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("修改云商品订单收货地址错误，" + e.getMessage(), e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
